const express = require("express");
const router = express.Router();
const Danmu = require("../controllers/danmuController");
const danmuObj = new Danmu();
const Jwt = require("../common/jwt");

// 添加弹幕
// 请求地址：http://localhost:3001/api/danmu/add
// 参数：content, color(可选), speed(可选), position(可选), token
router.post("/add", async (req, res) => {
  let { content, color, speed, position } = req.body;
  let token = req.headers.token || req.body.token;

  if (!token || !content) {
    res.status(400).json({
      code: -1,
      msg: "缺少参数"
    });
    return;
  }

  // 校验token
  let result = new Jwt(token).verifyToken();
  if (result.code == 200) {
    const user_id = result.info.data;
    await danmuObj.add(user_id, content, color, speed, position, 'published')
      .then(
        result => {
          res.status(200).json(result);
        },
        err => {
          res.status(500).json(err);
        }
      );
  } else {
    res.status(401).json({
      code: -1,
      msg: "您尚未登录"
    });
  }
});

// 获取弹幕列表（分页）
// 请求地址：http://localhost:3001/api/danmu/list
// 参数：page_num, page_size
router.post("/list", async (req, res) => {
  let { page_num, page_size } = req.body;

  // 默认分页参数
  page_num = page_num || 1;
  page_size = page_size || 10;

  await danmuObj.getList(page_num, page_size)
    .then(
      result => {
        res.status(200).json(result);
      },
      err => {
        res.status(500).json(err);
      }
    );
});

// 获取所有弹幕（不分页，用于弹幕显示）
// 请求地址：http://localhost:3001/api/danmu/all
// 参数：无
router.get("/all", async (req, res) => {
  await danmuObj.getAll()
    .then(
      result => {
        res.status(200).json(result);
      },
      err => {
        res.status(500).json(err);
      }
    );
});

// 删除弹幕
// 请求地址：http://localhost:3001/api/danmu/delete
// 参数：id, token
router.post("/delete", async (req, res) => {
  let { id } = req.body;
  let token = req.headers.token || req.body.token;

  if (!token || !id) {
    res.status(400).json({
      code: -1,
      msg: "缺少参数"
    });
    return;
  }

  // 校验token
  let result = new Jwt(token).verifyToken();
  if (result.code == 200) {
    const user_id = result.info.data;
    await danmuObj.delete(id, user_id)
      .then(
        result => {
          res.status(200).json(result);
        },
        err => {
          res.status(500).json(err);
        }
      );
  } else {
    res.status(401).json({
      code: -1,
      msg: "您尚未登录"
    });
  }
});

// 获取用户的所有弹幕
// 请求地址：http://localhost:3001/api/danmu/user
// 参数：page_num, page_size, token
router.post("/user", async (req, res) => {
  let { page_num, page_size } = req.body;
  let token = req.headers.token || req.body.token;

  if (!token) {
    res.status(401).json({
      code: -1,
      msg: "您尚未登录"
    });
    return;
  }

  // 校验token
  let result = new Jwt(token).verifyToken();
  if (result.code == 200) {
    const user_id = result.info.data;
    page_num = page_num || 1;
    page_size = page_size || 10;

    await danmuObj.getUserDanmus(user_id, page_num, page_size)
      .then(
        result => {
          res.status(200).json(result);
        },
        err => {
          res.status(500).json(err);
        }
      );
  } else {
    res.status(401).json({
      code: -1,
      msg: "您尚未登录"
    });
  }
});

// 管理员获取所有弹幕列表
// 请求地址：http://localhost:3001/api/danmu/admin/list
// 参数：page_num, page_size, keyword(可选), token
router.post("/admin/list", async (req, res) => {
  let { page_num, page_size, keyword } = req.body;
  let token = req.headers.token || req.body.token;

  if (!token) {
    res.status(401).json({
      code: -1,
      msg: "您尚未登录"
    });
    return;
  }

  // 校验token
  let result = new Jwt(token).verifyToken();
  if (result.code == 200) {
    page_num = page_num || 1;
    page_size = page_size || 10;

    await danmuObj.getAllDanmus(page_num, page_size, keyword)
      .then(
        result => {
          res.status(200).json(result);
        },
        err => {
          res.status(500).json(err);
        }
      );
  } else {
    res.status(401).json({
      code: -1,
      msg: "您尚未登录"
    });
  }
});

// 管理员删除弹幕
// 请求地址：http://localhost:3001/api/danmu/admin/delete
// 参数：id, token
router.post("/admin/delete", async (req, res) => {
  let { id } = req.body;
  let token = req.headers.token || req.body.token;

  if (!token || !id) {
    res.status(400).json({
      code: -1,
      msg: "缺少参数"
    });
    return;
  }

  // 校验token
  let jwtResult = new Jwt(token).verifyToken();
  if (jwtResult.code == 200) {
    const userId = jwtResult.info.data;
    const db = require("../common/db/index");

    try {
      // 验证是否为管理员
      const roleSql = 'SELECT role FROM pre_user WHERE id = ?';
      const roleResult = await db.query(roleSql, [userId]);
      if (roleResult.length == 0 || roleResult[0].role != '1') {
        res.status(403).json({ code: -1, msg: "权限不足，只有管理员可以删除弹幕" });
        return;
      }

      await danmuObj.adminDelete(id)
        .then(
          result => {
            res.status(200).json(result);
          },
          err => {
            res.status(500).json(err);
          }
        );
    } catch (error) {
      res.status(500).json({ code: -1, msg: "删除弹幕失败", error: error.message });
    }
  } else {
    res.status(401).json({
      code: -1,
      msg: "您尚未登录"
    });
  }
});

module.exports = router;

